package com.fm.jbsql.util;

import java.io.*;
import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 * User: otacar
 * Date: 17/1/2007
 * Time: 23:55:51
 * SVN entries file parser
 */
public class SvnEntryReader {
    /**
     * handler for svn entries
     */
    private SvnEntryPlainTextHandler contentHandler;

    /**
     * Set entry handler
     * @param handler
     */
    public void setContentHandler(SvnEntryPlainTextHandler handler) {
        contentHandler = handler;
    }

    /**
     * Parse svn entries file, fill attributes and pass to handler
     * @param f
     * @throws JbsqlException
     */
    public void parse(File f) throws JbsqlException {
        String s;
        HashMap attrs = new HashMap();
        int attributeIdx = 0, entryIdx = 0;
        try {
            BufferedReader is = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF8"));
            // check first line, it should contain value of >= 4
            if ( (s=is.readLine()) == null || s.trim().length() == 0 || s.charAt(0) < 4 ) throw new JbsqlException("SVN_01", "", null);
            while ( (s=is.readLine()) != null ) {
                if ( attributeIdx++ >= 32 ) throw new JbsqlException("SVN_02", "" + entryIdx, null);

                // end of element
                if ( s.length() == 1 && 0xC == s.charAt(0) ) {
                    attributeIdx = 0;
                    entryIdx++;
                }
                s = s.trim();
                switch (attributeIdx) {
                    case 0: // end of element
                        if ( contentHandler != null ) contentHandler.startElement(attrs);
                        attrs.clear();
                        break;
                    case 1: // name
                        attrs.put("name", (s.length() == 0 ? "." : s));
                        break;
                    case 2: // kind
                        if ( s.length() == 0 ) throw new JbsqlException("SVN_03", "" + entryIdx, null);
                        attrs.put("kind", s);
                        break;
                    case 6: // schedule
                        attrs.put("schedule", (s.length() == 0 ? null : s));
                        break;
                    case 10: // revision
                        //if ( s.length() == 0 ) throw new JbsqlException("SVN_04", "" + entryIdx, null);
                        attrs.put("committed-rev", s);
                        break;
                    default:
                        break;
                }

            }
            is.close();
        }
        catch (IOException ex) {
            throw new JbsqlException("IOE_04", f.getName(), ex);
        }
    }
}
